//
//  ConversationSettingViewController.m
//  huashiedu
//
//  Created by oceans on 2018/9/13.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "ConversationSettingViewController.h"
#import "HttpRequest.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "GroupUserModel.h"
#import "MessageSettingCollectionViewCell.h"
#import "MessageSettingCollectionReusableView.h"
#import "ChangeGroupNameViewController.h"
#import "MessageHistoryViewController.h"

@interface ConversationSettingViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MessageSettingHeaderDelegate>

@property (strong, nonatomic) UICollectionView *collection;
@property (strong, nonatomic) NSMutableArray <GroupUserModel *> *dataArr;
@property (strong, nonatomic) MetaModel *model;
@end

@implementation ConversationSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.dataArr = [NSMutableArray array];
    [self setupView];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)loadData {
    
    if (_groupId) {
        __weak typeof(self) weakself = self;
        [HttpRequest getURL:kget_ry_groupuser paras:@{@"id": _groupId} showProgress:NO successful:^(id  _Nullable result) {
            
            NSArray *array = result[@"data"][@"items"];
            for (NSDictionary *dic in array) {
                GroupUserModel *model = [[GroupUserModel alloc] initWithDic:dic];
                [weakself.dataArr addObject:model];
            }
            [weakself.collection reloadData];
            
            MetaModel *model = [[MetaModel alloc] initWithDic:result[@"data"][@"meta"]];
            if (model.currentPage == model.pageCount || model.pageCount == 0) {
                [weakself.collection.footer endRefreshingWithNoMoreData];
            }else {
                weakself.model = model;
            }
        } failed:nil];
    }
}

- (void)loadMoreData {
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kget_ry_groupuser paras:@{@"id": _groupId, @"page": [NSNumber numberWithInt:self.model.currentPage + 1]} showProgress:NO successful:^(id  _Nullable result) {
        
        NSArray *array = result[@"data"][@"items"];
        for (NSDictionary *dic in array) {
            GroupUserModel *model = [[GroupUserModel alloc] initWithDic:dic];
            [weakself.dataArr addObject:model];
        }
        [weakself.collection reloadData];
        
        MetaModel *model = [[MetaModel alloc] initWithDic:result[@"data"][@"meta"]];
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            [weakself.collection.footer endRefreshingWithNoMoreData];
        }else {
            [weakself.collection.footer endRefreshing];
            weakself.model = model;
        }
    } failed:^(int code, NSString *errMsg) {
        [weakself.collection.footer endRefreshing];
    }];
    
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"聊天信息";
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - XNavigationHeight) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    [self.view addSubview:_collection];
    
    [self.collection registerNib:[UINib nibWithNibName:@"MessageSettingCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MessageSettingCollectionViewCell"];
    [_collection registerNib:[UINib nibWithNibName:@"MessageSettingCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MessageSettingCollectionReusableView"];
    self.collection.footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(17, 21, 10, 21);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 13.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 20.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    float width = (ScreenWidth - 42.0 - 40.0) / 5.0;
    return CGSizeMake(width, width * 1.5);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    return CGSizeMake(ScreenWidth, ScreenWidth * 1.1);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        
        MessageSettingCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MessageSettingCollectionReusableView" forIndexPath:indexPath];
        view.delegate = self;
        view.nameLabel.text = [NSString stringWithFormat:@"%@（共%d人）", self.messageModel.name, self.messageModel.nums];
        return view;
    }
    return nil;
}

- (void)headerChangeGroupName {
    
    ChangeGroupNameViewController *change = [[ChangeGroupNameViewController alloc] init];
    change.group_id = self.groupId;
    change.model = self.messageModel;
    [self.navigationController pushViewController:change animated:YES];
}

- (void)headerShowMessageList {
    
    MessageHistoryViewController *conversationVC = [[MessageHistoryViewController alloc] init];
    conversationVC.displayUserNameInCell = YES;
    conversationVC.conversationType = ConversationType_GROUP;
    conversationVC.targetId = [NSString stringWithFormat:@"%d", self.messageModel._id];
    conversationVC.title = [NSString stringWithFormat:@"%@（共%d人）", self.messageModel.name, self.messageModel.nums];
    conversationVC.messageModel = self.messageModel; [self.navigationController pushViewController:conversationVC animated:YES];
}

- (void)headerexitGroup {
    __weak typeof(self) weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"确定退出群聊?" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself exitGroup];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)exitGroup {
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kexit_group paras:@{@"group_id": self.groupId} showProgress:YES successful:^(id  _Nullable result) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"exitGroup" object:nil userInfo:@{@"groupId": weakself.groupId}];
        [weakself.navigationController popToRootViewControllerAnimated:YES];
    } failed:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageSettingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MessageSettingCollectionViewCell" forIndexPath:indexPath];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(MessageSettingCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GroupUserModel *model = _dataArr[indexPath.item];
    cell.textLabel.text = model.name;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
}

@end
